<template>
  <div>
    <TopFilter
      ref="topfilter"
      :list="topFilterList"
      :cols="3"
      labelWidth="100"
      @filterChange="changeHandle"
      @onCollapse="collapseHandle"
    ></TopFilter>
    <!-- 分配 -->
    <el-dialog
      :visible.sync="consultVisible"
      title="选择IS专员"
      :type="consultHandleType"
      :rowData="consultFormData"
      width="80%"
    >
      <el-radio-group v-model="radio">
        <el-radio
          v-for="(item, index) in consults"
          :key="index"
          style="width:100px"
          :label="item.consultantId"
        >{{ item.name }}</el-radio>
      </el-radio-group>
      <div :style="{
          marginTop: '10px',
          textAlign: 'right'
        }">
        <el-button @click="consultcloseVisible">取 消</el-button>
        <el-button type="primary" @click="consultHandler">确 定</el-button>
      </div>
    </el-dialog>
    <FilterTable
      ref="table"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'records'"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="selectChangeHandle"
      columnsRef="potenCus_customer_potenCusManageOEM_index_01"
    >
      <template slot="controls">
        <multiuse-button
          size="small"
          type="primary"
          :click="addHandle"
          v-show="bbShow"
          :auth-list="auths"
          auth-mark="/api/cluecenter/jk/clue/editClue/add"
        >新增</multiuse-button>
        <multiuse-button
          size="small"
          type="primary"
          :click="importHandle"
          v-show="bbShow"
          :auth-list="auths"
          auth-mark="/api/cluecenter/jk/clue/importClueByExcel"
        >导入</multiuse-button>

        <multiuse-button
          size="small"
          type="primary"
          :click="exportHandle"
          v-show="bbShow"


        >导出</multiuse-button>
       <!--
           :auth-list="auths"
         auth-mark="/api/cluecenter/jk/clue/exportClueByExcel" -->
        <multiuse-button
          size="small"
          type="primary"
          :click="downHandle"
          v-show="bbShow"
          :auth-list="auths"
          auth-mark="/api/cluecenter/jk/clue/downloadClueModel"
        >模板下载</multiuse-button>
        <multiuse-button
          size="small"
          type="primary"
          :click="editDealer"
          v-show="bbShow"
          :auth-list="auths"
          auth-mark="/api/cluecenter/jk/clue/editOwnerCode"
        >修改经销商</multiuse-button>
        <multiuse-button
          size="small"
          type="primary"
          :click="updateClues"
          v-show="bbShow"
          :auth-list="auths"
          auth-mark="/api/cluecenter/jk/clue/updClues"
        >更新线索</multiuse-button>
        <multiuse-button
          size="small"
          type="primary"
          :click="sendCleaning"
          v-show="bbShow"
          :auth-list="auths"
          auth-mark="/api/cluecenter/jk/clue//sendCC?clueIds=${id}"
        >发送清洗</multiuse-button>

        <multiuse-button
          size="small"
          type="primary"
          v-show="fpShow"
          :click="changeHandleDistribution"
        >操作分配</multiuse-button>
        <multiuse-button
          size="small"
          type="primary"
          v-show="fpShow"
          :click="changeHandleTransfer"
        >操作转移</multiuse-button>
        <multiuse-button size="small" type="primary" v-show="ddShow" :click="iReturn">返回</multiuse-button>

        <multiuse-button size="small" type="primary" v-show="aaShow" :click="distribution">分配</multiuse-button>
        <multiuse-button size="small" type="primary" v-show="ccShow" :click="distribution">转移</multiuse-button>
      </template>
    </FilterTable>
    <Drawer
      :visible.sync="visible"
      :title="dialogTitle"
      :width="1100"
      destroyOnClose
      :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }"
    >
      <OEMmodel :type="handleType" :rowData="formData" @close="closeHandler" />
    </Drawer>
    <BaseDialog
      :visible.sync="UploadFileIsShow"
      title="导入"
      destroyOnClose
      :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }"
    >
      <!-- <UploadFile
        :action-url="actionUrl"
        :initial-value="form.fileList"
        :autoUpload='false'
        @change="successHandler"
        @error="errorHandler"
        :fileTypes="['xls','xlsx']"
      >选择导入文件
      </UploadFile>-->
      <importFile
        title="导入"
        actionUrl="/api/cluecenter/jk/clue/importClues"
        @close="closeImportHandler"
      />
    </BaseDialog>
    <BaseDialog
      :visible.sync="UploadFileIsShow_upload"
      title="更新线索"
      destroyOnClose
      :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }"
    >
      <!-- <UploadFile
        :action-url="actionUrl_upload"
        :initial-value="form.fileList_upload"
        :autoUpload='false'
        @change="successHandler_upload"
        @error="errorHandler_upload"
        :fileTypes="['xls','xlsx']"
      >选择更新文件
      </UploadFile>-->

      <importFile
        title="更新"
        actionUrl="/api/cluecenter/jk/clue/updateClues"
        @close="closeHandler_upload"
      />
    </BaseDialog>
    <BaseDialog
      :visible.sync="visibleDealer"
      title="修改经销商"
      destroyOnClose
      :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }"
    >
      <searchDealers
        :rowData="formDataDL"
        :selectList="selectClueIds"
        @close="closeHandler_Dealer"
      />
    </BaseDialog>
    <!-- 选择经销商 -->
    <BaseDialog
      :visible.sync="visibleJXS"
      title="选择经销商"
      width="70%"
      destroyOnClose
      :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }"
    >
      <TopFilter
        :list="topFilterListJXS"
        :cols="3"
        labelWidth="100"
        @filterChange="changeHandleJXS"
        @onCollapse="collapseHandle"
      ></TopFilter>
      <div class="DepartmentWrap clearfix" v-if="this.visibleJXS">
        <!-- 左侧树 -->
        <div class="leftTree">
          <span :class="sanjiao"></span>
          <el-tree :data="dataTree" :props="defaultProps" @node-click="handleNodeClick"></el-tree>
        </div>
        <!-- 右侧内容 -->
        <div class="rightContent">
          <FilterTable
            ref="tableJXS"
            :columns="columnsJXS"
            :dataSource="dataSource"
            height="auto"
            :onRowSelectChange="onRowSelectChange"
            :onColumnsChange="columns => (this.columns = columns)"
          >
            <!-- <template slot="controls" slot-scope="props">
                <el-button size="small" type="primary" icon="el-icon-plus" @click="addHandle(props)">新增</el-button>
            </template>-->
          </FilterTable>
        </div>
      </div>
      <div style="text-align: center;margin-top: 20px;">
        <el-button size="small" type="primary" @click="confirmJSX">确定</el-button>
        <el-button size="small" type="primary" @click="cancle">关闭</el-button>
      </div>
    </BaseDialog>
    <!-- 来源渠道弹窗 -->
    <BaseDialog
      title="来源渠道查询"
      :visible.sync="visibleSource"
      width="1000px"
      destroyOnClose
      :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }"
    >
      <sourceMadal ref="addDialogRef" selectType="single" @close="closeSource" />
    </BaseDialog>
  </div>
</template>

<script>
import { queryClueSourceList, getCompanyOrgIsMerge, getOrgType, getDealerArea, getOrgTypeForMin } from '@/api/potenCus/customer/potenCusManage';
import { vehicleConfigurationNew } from '@/api/retail/salesmanage/confirmcar'; //获取六级菜单
import { queryPotenCusOEM, verifications, downloadTemplate, exportClues, sendCleaningINFO, getTemperatureList , exporturl} from '@/api/potenCus/customer/potenCusManageOEM';
import { dictionary } from '@/utils/dictMixin';
import { getAllColorByAppIdAndType } from '@/api/potenCus/customer/potenCusManage';
import { authority } from '@/utils/authMixin';
import { getUsersByPosition } from '@/api/potenCus/basePlate/basePlateFail/index';
import { exportExcelFile } from '@/utils/index';
import { getUserOrgId, getUserId } from '@/assets/js/auth';
import { getUserByIdCMSNew } from '@/api/common/auth/roleManage';
import { formatDates, formatDat } from '@/utils/validate';
import OEMmodel from './OEMmodel';
import searchDealers from './addOEMdiaolg/searchDealers';
import { getChildOrgTreeList, getChildOrgdetail } from '@/api/common/org/companyOrgManage';
import sourceMadal from '@/pages/cms-common/source/index';
import { getAppId } from '@/assets/js/auth';
import { getLoginUser } from '@/api/cms-api/projectOperating/program/departmentInquire'; //获取登录信息
import { getUncounselorListCenter, queryCluesPrameterCenter, updateCluesISpersonnel } from '@/api/potenCus/basedata/cluesPrameter';
export default {
  name: 'PotenCusManageOEM',
  mixins: [dictionary, authority],
  components: {
    OEMmodel,
    searchDealers,
    sourceMadal
  },
  data() {

    return {
      topFilterList: this.createTopFilters(),
      topFilterListJXS: this.createTopFiltersJXS(),
      columns: this.createTableColumns(),
      columnsJXS: this.createTableColumnsJXS(),
      fetchApi: queryPotenCusOEM,
      fetchParams: this.initFetchParams(),
      selectedRows: [], //选中列表中的行
      visible: false,
      fpShow: false,
      consults: [],
      clueIds: '',
      topFilterlength: null,
      visibleDealer: false,
      UploadFileIsShow: false,
      distributionFlag: '',
      distributionShow: false,
      UploadFileIsShow_upload: false,
      consultVisible: false,
      aaShow: false,
      bbShow: true,
      ccShow: false,
      ddShow: false,
      formData: {},
      handleType: '',
      formDataDL: {},
      dialogTitle: '',
      conf: { add: '新增', edit: '编辑', show: '明细', import: '导入', export: '导出', down: '下载', upload: '更新' },
      form: {
        fileList: [],
        fileList_upload: []
      },
      actionUrl: '/api/cluecenter/jk/clue/importClueByExcel',
      actionUrl_upload: '/api/cluecenter/jk/clue/updClues',
      visibleJXS: false,
      dataTree: [],
      bjShow: true,
      consultHandleType: '',
      consultFormData: {},
      consultVisible: false,
      radio: '',
      defaultProps: {
        children: 'children',
        label: 'text'
      },
      dataSource: [],
      params: {
        orgId: 0,
        type: 10041002
      },
      sanjiao: 'sanjiao',
      dataSourceList: '',
      selectClueIds: [], // 当前所选线索
      visibleSource: false, //来源渠道是否显示
      clueSource: '',
      clueSourceName: ''
    };
  },
  created() {
    let userOrgId = getUserOrgId();
    let userId = getUserId();
    getUserByIdCMSNew({ userId: userId, userOrgId: userOrgId }).then(result => {
      if (result.resultCode === 200) {
        if (null != result.data.positionCode && -1 != result.data.positionCode.search('10061050')) {
          this.fpShow = true;
          this.bjShow = false;
        }
      }
    });
    this.init();
    // this.getClueTree()
    this.getHotist();
  },
  methods: {
    initFetchParams() {
      let userOrgId = getUserOrgId();
      return { userOrgId: userOrgId, xhrAbort: true };
    },
    async consultHandler() {
      let userOrgId = await getUserOrgId();
      if (this.radio) {
        updateCluesISpersonnel({ clueIds: this.clueIds, isPersonnel: this.radio }).then(result => {
          if (result.resultCode === 200) {
            this.fetchParams = Object.assign({}, { distribution: this.distributionFlag, clueSourceIds: this.clueSource, userOrgId: userOrgId });
            this.$message({
              type: 'success',
              message: '操作成功!'
            });
            this.consultVisible = false;
          }
        });
      } else {
        this.$message.info('请先选择顾问');
      }
    },
    consultcloseVisible() {
      this.radio = '';
      this.consultVisible = false;
      this.approvalVisible = false;
    },

    async init() {
      // 查询所属顾问
      let params = {
        positionCode: '10061051',
        menuId: 204010
      };
      queryCluesPrameterCenter({ consultantId: 100000 }).then(result => {
        console.log(result, '1234567876543');
        if (result.resultCode === 200) {
          this.topFilterList.find(item => item.fieldName === 'isPersonnel').itemList = result.data.map(x => ({ value: `${x.consultantId}`, text: x.name }));
          let orginList = result.data;
          let index = 0;
          orginList.forEach(item => {
            this.consults.push(item);
            index = index + 1;
          });

          console.log(this.consults, '1234567876543');
          // this.consultantList = orginList.filter((item, index, array) => {
          //   return array.findIndex(el => el.consultantId == item.consultantId) === index;
          // });
          //this.topFilterList.find(item => item.fieldName === 'consultant').itemList = this.consultantList.map(x => ({ value: x.userId, text: x.userName, userCode: x.userCode }));
          // this.consults = this.consultantList;
        }
        // console.log(result,"result")
        // this.topFilterList.find(item=>item.fieldName == "consultant").itemList= result.data.map(x => ({ value: x.userId, text: x.userName ,userCode:x.userCode}));
      });
      // 车型
      vehicleConfigurationNew(0, { isUnlimited: 10041001 })
        .then(res => {
          this.topFilterList.find(item => item.fieldName === 'initStr').itemList = res.data;
        })
        .catch(err => {
          // console.log(err)
        });

      // 查询内饰颜色
      let user = await getLoginUser({});
      if ('beijing' == user.data.appId) {
        this.topFilterList.find(item => item.fieldName === 'interiorColor').hidden = true;
      } else {
        //this.distributionShow = true;
      }

      //console.log(user.data.appId, 'we2rwevsdvdv');
      await getAllColorByAppIdAndType({ appId: user.data.appId, colorType: '16081001' }).then(result => {
        this.topFilterList.find(item => item.fieldName === 'interiorColor').itemList = result.data.map(x => ({ value: `${x.colorId}`, text: x.colorName }));
      });
    },
    createTopFilters() {
      return [
        /*20191126成--让去掉
         {
          type: 'SELECT',
          label: '所属区域',
          fieldName: 'orgId',
          placeholder: '请选择',
          itemList: [],
          change:val=>{
            console.log('val', val)
            if(!val){
              this.topFilterList.find(item => item.fieldName ==='ownerCodes').initialValue = ''
            } else {
              getDealerArea(val,'','').then(res =>{
                console.log('val', res)
                if (res.resultCode === 200) {
                  // this.formList2.find(item => item.fieldName ==='ownerCodes').itemList =
                }
              })
            }
          },
        }, */
        {
          type: 'INPUT',
          label: '经销商',
          fieldName: 'ownerCodes',
          placeholder: '请输入',
          unitRender: () => {
            return <el-button slot="append" icon="el-icon-circle-plus" onClick={this.openDriveCancel}></el-button>;
          },
          itemList: []
        },
        {
          type: 'INPUT',
          label: '关键字',
          fieldName: 'search',
          placeholder: '请输入'
        },
        // {
        //   type: 'SELECT',
        //   label: '线索状态',
        //   fieldName: 'clueStatus',
        //   placeholder: '请选择',
        //   itemList: this.preDictList(['7000', '7067'])
        // },
        {
          type: 'MULTIPLE_SELECT',
          label: '线索状态',
          fieldName: 'clueStatusList',
          placeholder: '请选择',
          initialValue: '',
          itemList: this.preDictList(['7000', '7067'])
        },
        {
          type: 'SELECT',
          label: '是否到店',
          fieldName: 'toShop',
          placeholder: '请选择',
          itemList: this.createDictList('1004')
        },
        {
          type: 'SELECT',
          label: '是否试驾',
          fieldName: 'testDrive',
          placeholder: '请选择',
          itemList: this.createDictList('1004')
        },
        {
          type: 'SELECT',
          label: '客户类型',
          fieldName: 'customerType',
          placeholder: '请选择',
          itemList: this.createDictList('1523')
        },
        // {
        //   type: 'SELECT',
        //   label: '线索类型',
        //   fieldName: 'clueType',
        //   placeholder: '请选择',
        //   itemList: this.createDictList('7019')
        // },
        {
          type: 'MULTIPLE_SELECT',
          label: '线索类型',
          fieldName: 'clueTypeList',
          placeholder: '请选择',
          initialValue: '',
          itemList: this.createDictList('7019')
        },
        {
          type: 'SELECT',
          label: '订金类型',
          fieldName: 'depositType',
          placeholder: '请选择',
          initialValue: '',
          itemList: this.createDictList('8050')
        },
        {
          type: 'SELECT',
          label: '线索热度',
          fieldName: 'clueLevel',
          placeholder: '请选择',
          itemList: []
        },
        // {
        //   type: 'INPUT_TREE',
        //   label: '来源渠道',
        //   fieldName: 'clueSource',
        //   placeholder: '请选择',
        //   defaultExpandAll: true,
        //   itemList: []
        // },
        {
          type: 'INPUT',
          label: '来源渠道',
          fieldName: 'clueSourceName',
          placeholder: '请选择',
          initialValue: '',
          unitRender: () => {
            return (
              <div>
                <el-button slot="append" icon="el-icon-search" onClick={() => this.sourceHandle()}></el-button>
                <el-button slot="append" icon="el-icon-delete" onClick={() => this.clearSourceHandle()}></el-button>
              </div>
            );
          }
        },
        {
          type: 'INPUT_CASCADER',
          label: '意向车型',
          fieldName: 'initStr',
          placeholder: '请选择',
          options: { titles: ['品牌', '车系', '车型', '配置', '选装', '颜色'] },
          itemList: []
        },

        {
          type: 'MULTIPLE_SELECT',
          label: '内饰颜色',
          fieldName: 'interiorColor',
          placeholder: '请选择',
          itemList: []
        },
        {
          type: 'RANGE_DATE',
          label: '采集时间',
          fieldName: 'collectBeginTime|collectFinshTime',
          placeholder: '请选择'
        },
        {
          type: 'INPUT',
          label: '清洗人',
          fieldName: 'ccCleanPerson',
          placeholder: '请选择',
        },
        {
          type: 'INPUT',
          label: '创建人',
          fieldName: 'createdByName',
          placeholder: '请输入'
        },
        {
          type: 'RANGE_DATE',
          label: '创建日期',
          fieldName: 'createBeginTime|createFinshTime',
          placeholder: '请选择'
        },
        {
          type: 'RANGE_DATE',
          label: '下发日期',
          fieldName: 'sendBeginTime|sendFinshTime',
          placeholder: '请选择'
        },
        {
          type: 'RANGE_DATE',
          label: '最后跟进时间',
          fieldName: 'lastFlowBeginTime|lastFlowFinshTime',
          placeholder: '请选择'
        },
        {
          type: 'SELECT',
          label: '线索评级等级',
          fieldName: 'mapClueLevel',
          hidden: getAppId()=='beijing'?false:true,
          placeholder: '请选择',
          itemList: [
            { value: 1, text: '一' },
            { value: 2, text: '二' },
            { value: 3, text: '三' },
            { value: 4, text: '四' },
            { value: 5, text: '五' }
          ]
        },
        // { 
        //   type: 'SELECT', 
        //   label: '是否店端自建', 
        //   fieldName: 'isDlrCreate', 
        //   placeholder: '请选择', 
        //   itemList: this.createDictList('1004') 
        // } 
      ];
    },

    createTopFiltersJXS() {
      return [
        {
          type: 'INPUT',
          label: '经销商代码',
          fieldName: 'dealerCode',
          placeholder: '请输入'
        },
        {
          type: 'INPUT',
          label: '经销商名称',
          fieldName: 'dealerName',
          placeholder: '请输入'
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 100,
          fixed: 'left',
          render: (props, h) => {
            if (true != this.bjShow) {
              return (
                <el-button size="mini" type="text" onClick={() => this.showHandle(props.row)}>
                  明细
                </el-button>
              );
            }
            return (
              <div>
                <multiuse-button
                  size="mini"
                  type="text"
                  onClick={() => this.editHandle(props.row)}
                  style={props.row.clueStatus != 70671005 ? { color: '#D9D9D9' } : {}}
                  auth-list={this.auths}
                  auth-mark={'/api/cluecenter/jk/clue/editClue'}
                >
                  编辑
                </multiuse-button>
                <el-button size="mini" type="text" onClick={() => this.showHandle(props.row)}>
                  明细
                </el-button>
              </div>
            );
          }
        },
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '线索类型',
          dataIndex: 'clueType',
          sorter: true,
          filter: true,
          align: 'center',
          filterType: 'checkbox',
          filterItems: this.createDictList('7019'),
          render: props => {
            return <span>{this.createDictText(props.row.clueType, '7019')}</span>;
          }
        },
        {
          title: '订金类型',
          dataIndex: 'depositType',
          sorter: true,
          filter: true,
          align: 'center',
          filterType: 'checkbox',
          filterItems: this.createDictList('8050'),
          render: props => {
            return <span>{this.createDictText(props.row.depositType, '8050')}</span>;
          }
        },
        {
          title: '订金金额',
          dataIndex: 'depositAmount',
          align: 'center',
          filterType: 'input'
        },
        {
          title: '线索状态',
          dataIndex: 'clueStatus',
          align: 'center',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.preDictList(['7000', '7067']),
          render: props => {
            return <span>{this.preDictHandler(props.row.clueStatus, ['7000', '7067'])}</span>;
          }
        },
        {
          title: '线索热度',
          dataIndex: 'clueLevelStr',
          sorter: true,
          align: 'center',
          filterType: 'input',
          filterItems: []
          // render: props => {
          //   return <span>{this.createDictText(props.row.clueLevel, '7018')}</span>;
          // }
        },
        {
          title: '是否试驾',
          dataIndex: 'testDrive',
          sorter: true,
          align: 'center',
          filterType: 'input'
        },
        {
          title: '清洗次数',
          dataIndex: 'clearNum',
          sorter: true,
          align: 'center',
          filterType: 'input'
        },
        {
          title: '所属区域',
          dataIndex: 'orgId',
          align: 'center',
          filterType: 'input'
        },
        {
          title: '经销商全称',
          dataIndex: 'ownerName',
          align: 'center',
          filterType: 'input'
        },
        {
          title: '经销商代码',
          dataIndex: 'dealerCode',
          align: 'center',
          filterType: 'input'
        },
        {
          title: '客户类型',
          dataIndex: 'customerType',
          filter: true,
          align: 'center',
          filterType: 'checkbox',
          filterItems: this.createDictList('1523'),
          render: props => {
            return <span>{this.createDictText(props.row.customerType, '1523')}</span>;
          }
        },
        {
          title: '线索评级等级',
          dataIndex: 'mapClueLevel',
          filter: true,
          hidden:getAppId()=='beijing'?false:true,
          align: 'center',
            render: props => {
             return <el-rate disabled={true} v-model={props.row.mapClueLevel}></el-rate>;
          }
        },
        {
          title: '客户名称',
          dataIndex: 'name',
          filter: true,
          align: 'center',
          filterType: 'input'
        },
        {
          title: '联系人名称',
          dataIndex: 'concatName',
          filter: true,
          align: 'center',
          filterType: 'input'
        },
        {
          title: '手机号码',
          dataIndex: 'phone',
          align: 'center',
          sorter: true,
          filterType: 'input'
        },
        {
          title: '省份',
          dataIndex: 'province',
          align: 'center',
          filterType: 'input'
        },
        {
          title: '城市',
          dataIndex: 'city',
          align: 'center',
          filterType: 'input'
        },
        {
          title: '区域',
          dataIndex: 'county',
          align: 'center',
          filterType: 'input'
        },
        {
          title: '地址',
          dataIndex: 'address',
          align: 'center',
          width: 180,
          filterType: 'input'
        },
        {
          title: '性别',
          dataIndex: 'gender',
          align: 'center',
          filterType: 'checkbox',
          filterItems: this.createDictList('1002'),
          render: props => {
            return <span>{this.createDictText(props.row.gender, '1002')}</span>;
          }
        },
        {
          title: '来源渠道',
          dataIndex: 'sourceStr',
          filter: true,
          width: 200,
          filterType: 'input'
        },
        {
          title: '来源备注',
          dataIndex: 'sourceRemark',
          width: 150,
          filterType: 'input'
        },
        {
          title: '他店转入',
          dataIndex: 'otherOrigin',
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('1004'),
          render: props => {
            return <span>{this.createDictText(props.row.otherOrigin, '1004')}</span>;
          }
        },
        {
          title: '意向品牌',
          dataIndex: 'brandName',
          filterType: 'input'
        },
        {
          title: '意向车系',
          dataIndex: 'seriesName',
          filterType: 'input'
        },
        {
          title: '意向车型',
          dataIndex: 'modelName',
          filterType: 'input'
        },
        {
          title: '意向配置',
          dataIndex: 'modelPackage',
          width: 250,
          filterType: 'input'
        },
        {
          title: '意向选装',
          dataIndex: 'modelOption',
          width: 250,
          filterType: 'input'
        },
        {
          title: '意向颜色（外饰）',
          dataIndex: 'modelColor',
          width: 180,
          filterType: 'input'
        },
        {
          title: '意向颜色（内饰）',
          dataIndex: 'modeIntrim',
          width: 180,
          filterType: 'input'
        },
        {
          title: '备注',
          dataIndex: 'remark',
          width: 150,
          filterType: 'input'
        },
        {
          title: '采集时间',
          dataIndex: 'handleTime',
          width: 150,
          filterType: 'RANGE_DATE'
        },
        {
          title: '首次跟进时间',
          dataIndex: 'firstFlowTime',
          width: 150,
          align: 'center'
        },
        {
          title: '最后跟进时间',
          dataIndex: 'lastFlowTime',
          width: 150,
          align: 'center'
        },
        {
          title: '是否按时首次联系',
          dataIndex: 'isFirstContact',
          align: 'center',
          filterType: 'input'
        },
        {
          title: '创建人',
          dataIndex: 'createAt',
          align: 'center',
          filterType: 'input'
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          width: 150,
          align: 'center'
          // render: props =>{
          //   // return <span>{ formatDates(props.row.createdAt) }</span>
          // }
        },
        {
          title: '下发时间',
          dataIndex: 'sendTime',
          width: 150
          // render: props =>{
          //   // return <span>{ formatDates(props.row.manufacturerIssueDate) } </span>
          // }
        },
        {
          title: '到店时间',
          dataIndex: 'inStore',
          width: 150
          // render: props =>{
          //   // return <span>{ formatDates(props.row.ddddd) } </span>
          // }
        },
        {
          title: '清洗人',
          dataIndex: 'ccCleanPerson',
          width: 150,
          align: 'center',
          filterType: 'input'
        },
        {
          title: '线索编号',
          dataIndex: 'clueId',
          width: 150,
          align: 'center',
          filterType: 'input'
          },
          {
            title: '首次试驾时间',
            dataIndex: 'firstTestDriveTime',
            width: 200,
            align: 'center',
            filterType: 'input'

          },
          {
          title: '是否店端自建',
          dataIndex: 'isDealer',
          align: 'center',
          filterType: 'checkbox',
          filterItems: this.createDictList('1004'),
          render: props => {
            return <span>{this.createDictText(props.row.isDealer, '1004')}</span>;
          }
        },
        {
          title: 'CC首次清洗时间',
          dataIndex: 'ccFirsCleantTime',
          align: 'center',
     
        },
        {
          title: 'CC清洗备注',
          dataIndex: 'ccInvalidReason',
          align: 'center',
    
        },
        {
          title: '是否店CC厂家客服跟进端自建',
          dataIndex: 'ccOemActioned',
          align: 'center' 
        },
        {
          title: 'CC厂家客服跟进人员名称',
          dataIndex: 'ccOemActionedBy',
          align: 'center',
      
        },
        {
          title: 'CC及时清洗时长',
          dataIndex: 'ccCleanLong',
          align: 'center',
   
        },
        {
          title: '是否厂端客服清洗',
          dataIndex: 'isOemClean',
          align: 'center',
          render: props => {
            return <span>{this.createDictText(props.row.isOemClean, '1004')}</span>;
          }
        }

      ];
    },
    createTableColumnsJXS() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '经销商代码',
          dataIndex: 'dealerCode',
          filterType: 'input',
          filterItems: [],
          editable: false
          // editType: 'select',
          // editItems: this.createDictList('7021')
        },
        {
          title: '经销商名称',
          dataIndex: 'dealerName',
          filterType: 'input',
          filterItems: [],
          editable: false
          // editType: 'select',
          // editItems: []
        }
      ];
    },
    //经销商
    openDriveCancel() {
      this.visibleJXS = true;
      this.topFilterList.find(item => item.fieldName == 'ownerCodes').initialValue = '';
      this.dataSourceList = '';
      this.getVueTree();
    },
    // getVueTree
    async getVueTree() {
      this.dataTree = [];
      // 当前经销商有无小区 是否合并
      const res = await getCompanyOrgIsMerge();
      console.log('是否合并', res);
      // isDisArea： 10041001 只有大区   10041002 ：有小区
      // isMerge ：10041001 销售售后合并  10041002 ：不合并
      let { isDisArea, isMerge } = res.data;
      // 1. 不合并只大区 传15061005
      if (isDisArea == 10041001 && isMerge == 10041002) {
        // 查询经销商代码
        const res1 = await getOrgType(15061005);
        console.log('经销商代码1', res1.data);
        if (res1.resultCode == 200) {
          this.dataTree = res1.data.map(x => ({ value: x.orgId, text: x.orgName }));
        }
      }
      // 2. 不合并大小区 传15061005 ,15061007
      if (isDisArea == 10041002 && isMerge == 10041002) {
        let orgType1 = '15061005';
        const res2 = await getOrgType(orgType1);
        console.log('经销商代码2', res2);
        if (res2.resultCode == 200) {
          this.dataTree = res2.data.map(x => ({ value: x.orgId, text: x.orgName, orgType: x.orgType, children: [] }));
        }
      }
      // 3. 合并大区 传15061004
      if (isDisArea == 10041001 && isMerge == 10041001) {
        const res3 = await getOrgType(15061014);
        console.log('经销商代码3', res3);
        if (res3.resultCode == 200) {
          this.dataTree = res3.data.map(x => ({ value: x.orgId, text: x.orgName }));
        }
      }
      // 4. 合并大小区 传15061014， 15061015
      if (isDisArea == 10041002 && isMerge == 10041001) {
        let orgType2 = '15061014';
        const res4 = await getOrgType(orgType2);
        console.log('经销商代码4', res4);
        if (res2.resultCode == 200) {
          this.dataTree = res4.data.map(x => ({ value: x.orgId, text: x.orgName, orgType: x.orgType, children: [] }));
        }
      }
    },
    distribution() {
      if (!this.selectedRows.length) {
        this.$message.info('请先选择线索');
      } else {
        let ids = '';
        let flag = 0;
        this.selectedRows.forEach(item => {
          if (70671005 != item.clueStatus) {
            this.$message.info('只能分配待处理线索');
            flag = 1;
          }
          ids += item.clueId + ',';
        });
        if (1 != flag) {
          this.clueIds = ids;
          this.consultVisible = true;
        }
      }
    },
    //树节点
    handleNodeClick(data) {
      this.sanjiao = '';
      console.log(data, 'data');
      if (data != '' || data != 'undefined') {
        this.params.orgId = data.value;
        if (data.orgType && data.orgType == '15061005') {
          getOrgTypeForMin(data.value, 15061007).then(res => {
            console.log(res, '小区15061007');
            data.children = res.data;
          });
        } else if (data.orgType && data.orgType == '15061014') {
          getOrgTypeForMin(data.value, 15061015).then(res => {
            console.log(res, '小区15061015');
            data.children = res.data;
          });
        } else {
          getDealerArea(data.value, '', '').then(res => {
            console.log('根据事业部查询经销商', res);
            if (res.resultCode === 200) {
              this.dataSource = res.data.map((x, k) => ({ index: k, dealerCode: x.dealerCode, dealerName: x.dealerName }));
            }
          });
        }
      }
    },
    //表格数据变化时
    onRowSelectChange(row) {
      console.log(row, 'val');
      if (row && row.length == 1) {
        row.map(x => {
          this.dataSourceList = x.dealerCode;
        });
      } else {
        this.dataSourceList = '';
        row.map(x => {
          this.dataSourceList += x.dealerCode + ',';
        });
      }
    },
    //确定
    confirmJSX() {
      console.log(this.dataSourceList, 'this.dataSourceList');
      this.topFilterList.find(item => item.fieldName == 'ownerCodes').initialValue = '';
      if (this.dataSourceList) {
        this.topFilterList.find(item => item.fieldName == 'ownerCodes').initialValue = this.dataSourceList;
        this.visibleJXS = false;
        this.params.orgId = 0;
        this.params.type = 10041002;
      } else {
        this.$message({
          type: 'info',
          message: '请选择一条数据'
        });
      }
    },
    //关闭
    cancle() {
      this.visibleJXS = false;
      this.params.orgId = 0;
      this.params.type = 10041002;
    },
    // 线索热度定义
    async getHotist() {
      const res = await getTemperatureList();
      console.log('热度定义', res);
      if (res.resultCode === 200) {
        this.topFilterList.find(item => item.fieldName === 'clueLevel').itemList = res.data.map(x => ({ value: x.id, text: x.clueHeatName }));
      }
    },
    // 潜客来源
    async getClueTree() {
      const res = await queryClueSourceList();
      // // console.log('潜客来源', res)
      let treeList = res.data;
      treeList.forEach(el => (el.text = el.clueName));
      treeList.forEach(el => (el.value = el.id));
      treeList.forEach(el => (el.parentId = el.parentId));
      //只有叶子节点可以点击
      // let treeList = this.deepListClone([].concat(res.data));
      this.topFilterList.find(item => item.fieldName === 'clueSource').itemList = treeList;
    },
    // 来源渠道打开窗口 -传数据
    sourceHandle() {
      this.visibleSource = true;
    },
    // 来源渠道清除
    clearSourceHandle() {
      this.clueSource = '';
      this.clueSourceName = '';
      this.topFilterList.find(item => item.fieldName === 'clueSourceName').initialValue = '';
    },
    // 来源渠道关闭窗口 -返回数据
    closeSource(data) {
      console.log('-=-=-=-=-=-=-=', data);
      if (data.data && data.data.length > 0) {
        //循环返回数据
        let clueSourceArray = [];
        let clueSourceNameArray = [];
        data.data.forEach(x => {
          clueSourceArray.push(x.id);
          clueSourceNameArray.push(x.clueName);
        });
        this.clueSource = clueSourceArray.join(',');
        this.clueSourceName = clueSourceNameArray.join(',');
        //显示来源渠道名称
        this.topFilterList.find(item => item.fieldName === 'clueSourceName').initialValue = this.clueSourceName;
      }
      //关闭弹窗
      this.visibleSource = data.visible;
    },
    showHandler() {
      this.dialogTitle = `线索管理${this.conf[this.handleType]}`;
      this.visible = true;
    },
    addHandle() {
      this.handleType = 'add';
      this.showHandler();
    },
    selectChangeHandle(rows) {
      // console.log('rows', rows);
      // if (!rows.length) return;
      this.selectedRows = rows;
      // this.selectedRows.push(rows);
    },
    // 导入
    importHandle() {
      this.handleType = 'import';
      this.UploadFileIsShow = true;
      this.form.fileList = [];
    },
    successHandler(val) {
      // console.log(val,JSON.stringify(val), typeof val, Object.prototype.toString.call(val),"导入")
      if (val && val.length > 0) {
        this.form.fileList = val;
        this.UploadFileIsShow = false;
        this.fetchParams = { ...this.fetchParams };
        this.$message.success(val[0].url);
      } else {
      }
    },

    closeImportHandler(val) {
      if (val && val.length > 0) {
        if (val[0].url.errorList && val[0].url.errorList.length > 0) {
        } else {
          this.form.fileList = val[0].url.clue;
        }
        // this.$message.success(val[0].url)
      }

      this.UploadFileIsShow = false;
      // 重新加载
      this.fetchParams = { ...this.fetchParams };
    },
    errorHandler(val) {
      // console.log(val,"删除")
      // this.$message.error(val)
      // return false
    },
    successHandler_upload(val) {
      console.log(val, '更新线索');
      if (val && val.length > 0) {
        this.form.fileList_upload = val;
        this.UploadFileIsShow_upload = false;
        this.fetchParams = { ...this.fetchParams };
      }
    },
    errorHandler_upload(val) {
      console.log(val, '更新删除');
    },
    closeHandler_upload(val) {
      if (val && val.length > 0) {
        this.form.fileList_upload = val[0].url.clue;
        this.UploadFileIsShow_upload = false;
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
        // this.$message.success(val[0].url)
      } else {
        this.UploadFileIsShow_upload = false;
      }
    },
    // 导出
    async exportHandle(row) {

      // console.log('选择行', this.selectedRows);
      let json = Object.assign({}, { CODE: 'CODE_0000017' }, this.fetchParams);
      let res = await exporturl(json);

      if (res.resultCode == 200) {
        this.$router.push('/admin/auth/oem/downloadCenter');
      }
      // let params = JSON.parse(JSON.stringify(this.fetchParams));
      // await exportClues(params)
      //   .then(response => {
      //     console.log(response.data.size, 'response.data.size');
      //     console.log(response, 'response');
      //     if (response.data.size == 0) {
      //       this.$message({
      //         type: 'info',
      //         message: '数据量超过30000，请选装合适的时间段进行查询'
      //       });
      //     } else {
      //       exportExcelFile(response.data, '线索管理');
      //     }
      //   })
      //   .catch(err => {
      //     console.log(err);
      //   });
    },
    // 下载
    downHandle() {
      this.handleType = 'down';
      this.$confirm('下载模板', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          window.open('/download/OEM_MODEL.xlsx');
          this.$message({
            type: 'success',
            message: '下载成功!'
          });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '取消下载'
          });
        });
    },
    // 编辑经销商
    editDealer() {
      console.log('经销商', this.selectedRows);
      if (!this.selectedRows.length) {
        this.$message.info('请先选择线索');
      } else {
        if (this.selectedRows.length > 0) {
          let cannotEditClues = this.selectedRows.filter(item => item.clueStatus !== 70671005);
          if (cannotEditClues && cannotEditClues.length) {
            let str = cannotEditClues.map(item => item.$index + 1).join(',');
            // this.$message.info(`第${str}条数据不可修改经销商`);
            this.$message.info('当前存在不可编辑的经销商');
            return;
          } else {
            this.visibleDealer = true;
            this.selectClueIds = this.selectedRows.map(item => item.clueId);
            console.log('分配clueIds', this.selectClueIds);
          }
        }
      }
    },
    // 更新线索
    updateClues() {
      this.handleType = 'upload';
      this.UploadFileIsShow_upload = true;
    },
    // 发送清洗
    sendCleaning() {
      console.log('清洗线索', this.selectedRows);
      if (!this.selectedRows.length) {
        this.$message.info('请先选择线索');
      } else {
        // let data = []
        // this.selectedRows.forEach(item =>{
        //   data.push(item.clueId)
        // })
        // let ids = data.toString()
        let ids = '';
        this.selectedRows.forEach(item => {
          ids += item.clueId + ',';
        });
        console.log('ids', ids);
        sendCleaningINFO(ids).then(res => {
          console.log('清洗结果', res);
          if (res.resultCode == 200) {
            this.$message.success('发送成功');
            this.fetchParams = { ...this.fetchParams };
          }
        });
      }
    },
    editHandle(row) {
      console.log('编辑row', row);
      if (row.clueStatus != 70671005) {
        this.$message.info('该线索不可编辑，请知悉');
        return false;
      } else {
        this.handleType = 'edit';
        this.formData = row;
        this.showHandler();
      }
    },
    showHandle(row) {
      this.handleType = 'show';
      this.formData = row;
      this.showHandler();
    },
    async changeHandle(val) {
      if (val.clueSourceName == '') {
        this.clueSource = '';
      }
      let userOrgId = await getUserOrgId();
      val.isDlrCreate = 10041002; 
      this.fetchParams.xhrAbort = false;
      this.fetchParams = Object.assign({}, val, { distribution: this.distributionFlag, clueSourceIds: this.clueSource, userOrgId: userOrgId });
    },

    async changeHandleDistribution(val) {
      let userOrgId = await getUserOrgId();
      this.distributionFlag = 1;
      this.fpShow = false;
      this.bbShow = false;
      this.aaShow = true;
      this.ddShow = true;
      this.toggleBtnStatus(true);
      this.fetchParams = Object.assign({}, val, { distribution: 1, clueSourceIds: this.clueSource, userOrgId: userOrgId });
    },

    async changeHandleTransfer(val) {
      let userOrgId = await getUserOrgId();
      this.distributionFlag = 2;
      this.fpShow = false;
      this.bbShow = false;
      this.ccShow = true;
      this.ddShow = true;
      this.toggleBtnStatus(true);
      this.fetchParams = Object.assign({}, val, { distribution: 2, clueSourceIds: this.clueSource, userOrgId: userOrgId });
    },

    async iReturn(val) {
      this.fpShow = true;
      this.bbShow = true;
      this.ccShow = false;
      this.aaShow = false;
      this.ddShow = false;
      let userOrgId = await getUserOrgId();
      this.toggleBtnStatus(false);
      this.distributionFlag = '';
      this.fetchParams = Object.assign({}, val, { clueSourceIds: this.clueSource, userOrgId: userOrgId });
    },
    // 操作分配、转移，禁用、启用按钮
    toggleBtnStatus(flag) {
      let { topFilterlength } = this;
      console.log(topFilterlength);
      console.log(this.$refs.topfilter.$el.children[0][topFilterlength - 3]);
      if (flag) {
        // 禁用按钮
        this.$refs.topfilter.$el.children[0][topFilterlength - 3].disabled = true;
        this.$refs.topfilter.$el.children[0][topFilterlength - 2].disabled = true;
        this.$refs.topfilter.$el.children[0][topFilterlength - 3].classList.add('is-disabled');
        this.$refs.topfilter.$el.children[0][topFilterlength - 2].classList.add('is-disabled');
      } else {
        // 启用按钮
        this.$refs.topfilter.$el.children[0][topFilterlength - 3].disabled = false;
        this.$refs.topfilter.$el.children[0][topFilterlength - 2].disabled = false;
        this.$refs.topfilter.$el.children[0][topFilterlength - 3].classList.remove('is-disabled');
        this.$refs.topfilter.$el.children[0][topFilterlength - 2].classList.remove('is-disabled');
      }
    },

    //选择进销商
    changeHandleJXS(val) {
      console.log('123', val);
      getDealerArea('', val.dealerCode ? val.dealerCode : '', val.dealerName ? val.dealerName : '').then(res => {
        console.log('根据事业部查询经销商', res);
        this.dataSource = [];
        if (res.resultCode === 200) {
          this.dataSource = res.data.map((x, k) => ({ index: k, dealerCode: x.dealerCode, dealerName: x.dealerName }));
        }
      });
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    closeHandler(val, type) {
      this.visible = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    closeHandler_Dealer(val, type) {
      this.visibleDealer = val;
      if (type === 'refresh') {
        this.selectClueIds = [];
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    // 2021-5-6 16:43:48 qinjh 圣童和宏远确定后，线索状态过滤70001007（CC清洗中）、70001008（CC清洗无效）两项字典项；
    preDictList(codes = []) {
      let { createDictList } = this;
      return this.flatten(codes.map(item => createDictList(item))).filter(x => x.value != 70001006 && x.value != 70001007 && x.value != 70001008);
    },
    preDictHandler(val, codes = []) {
      let { createDictList } = this;
      let resultList = this.flatten(codes.map(item => createDictList(item)));
      let resultText = resultList && resultList.length > 0 ? resultList.find(item => item.value == val) : val;
      return resultText;
    },
    // 顾问列表
    // async getDirSalesName() {
    //   const res = await getDirSalesName({ menuId: 202050, positionCode: '10061015,10061012' });
    //   // console.log('车型信息', res)
    //   if (res.resultCode === 200) {
    //     this.consults = res.data;
    //   }
    // },
    flatten(list) {
      while (list.some(Array.isArray)) {
        list = [].concat(...list);
      }
      return list;
    }
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
    this.topFilterlength = this.$refs.topfilter.$el.children[0].length;
  }
};
</script>
<style lang="less" scoped>
.DepartmentWrap {
  // height: 79vh;
  height: 26vw;
  border: 1px solid #000;
  box-sizing: border-box;
  overflow: hidden;
  .leftTree {
    width: 36%;
    height: 100%;
    overflow-x: hidden;
    overflow-y: scroll;
    float: left;
    padding: 10px;
    box-sizing: border-box;
    position: relative;
  }

  .rightContent {
    width: 64%;
    height: 100%;
    overflow-x: hidden;
    overflow-y: scroll;
    float: left;
    box-sizing: border-box;
    padding: 10px;
    border-left: 2px solid #eee;
  }
}
.sanjiao {
  position: absolute;
  left: 18px;
  top: 19px;
  z-index: 99;
  width: 0;
  height: 0;
  border-top: 3px solid transparent;
  border-bottom: 5px solid transparent;
  border-left: 9px solid #ccc;
}
</style>
